//
//  QTLoginViewController.m
//  QTLifeCircle
//
//  Created by 徐腾 on 2017/1/17.
//  Copyright © 2017年 徐腾. All rights reserved.
//

#import "QTLoginViewController.h"

#import "HMCoreDataManager.h"
#import "UserInfo+CoreDataClass.h"
#import <SVProgressHUD.h>

@interface QTLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *hookButton;

@end

@implementation QTLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置弹框的最短时间
    [SVProgressHUD setMinimumDismissTimeInterval:0.5];
    
    //自定义navigationBar的背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top"] forBarMetrics:UIBarMetricsDefault];
    
}


- (IBAction)backHomeVC:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)loginButton:(id)sender {
    
    if (self.pwdTextField.text.length == 0 || self.accountTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"账号密码不正确"];
        return;
    }
    
    
    //1.创建查询请求  参数:查询的实体名(相当于sql中的表格)
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"UserInfo"];
    //设置查询请求的谓词(相当于sql中的where)
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.phoneNum CONTAINS %@",self.accountTextField.text];
    request.predicate = predicate;
    
    //2.使用上下文查询数据
    NSArray <UserInfo *>*arr = [kHMCoreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    
    if (arr.count > 0) {
        for (UserInfo *info in arr) {
            if ([info.phoneNum isEqualToString:self.accountTextField.text] && [info.password isEqualToString:self.pwdTextField.text]) {
                //弹框提示登录成功
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                
                //发送通知,让登录/注册按钮变成切换账号
                [[NSNotificationCenter defaultCenter] postNotificationName:@"succeess" object:nil];
                
                //退出控制器
                [self backHomeVC:nil];
            } else {
                [SVProgressHUD showErrorWithStatus:@"账号或者密码不正确"];
            }
        }
    }else {
        [SVProgressHUD showErrorWithStatus:@"账号或者密码不正确"];
    }
   
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
